package com.azh.server.datam.dataItem;

import java.sql.DataTruncation;
import java.util.Arrays;

import com.azh.server.common.SubArray;
import com.azh.server.datam.DataManager;
import com.azh.server.datam.DataManagerImpl;
import com.azh.server.datam.page.Page;
import com.azh.server.util.Parser;
import com.azh.server.util.Types;
import com.google.common.primitives.Bytes;

/**
 * @author zhaozhenhang <zhaozhenhang@kuaishou.com>
 * Created on 2022-04-25
 */
public interface DataItem {

    SubArray data();

    public void before();

    public void unBefore();

    public void after(long txId);

    public void release();

    public void lock();

    public void unlock();

    public void rLock();

    public void rUnLock();

    public Page page();

    public long getUid();

    public byte[] getOldRaw();

    public SubArray getRaw();

    public static void setDataItemRawInvalid(byte[] raw) {
        raw[DataItemImpl.of_valid] = (byte) 1;
    }

    /**
     * 从页面的offset处解析处dataItem
     * @param page
     * @param offset
     * @param dmi
     * @return
     */
    public static DataItem parseDataItem(Page page, short offset, DataManagerImpl dmi) {
        byte[] raw = page.getData();
        short size = Parser.parseShort(
                Arrays.copyOfRange(raw, offset + DataItemImpl.of_size, offset + DataItemImpl.of_data));
        short len = (short) (size + DataItemImpl.of_data);
        long uid = Types.addressToUid(page.getPageNumber(), offset);
        return new DataItemImpl(new SubArray(raw, offset, offset + len), new byte[len], page, uid, dmi);
    }

    public static byte[] wrapDataItemRaw(byte[] raw) {
        byte[] valid = new byte[1];
        byte[] size = Parser.shortToByte((short) raw.length);
        return Bytes.concat(valid, size, raw);
    }
}
